package com.sh.museum.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.sh.museum.R;
import com.sh.museum.common.Constants;
import com.sh.museum.utils.FileUtils;
import com.sh.museum.utils.SharedPrefUtil;
import com.sh.museum.view.NumberProgressBar;

import java.io.File;
import java.text.DecimalFormat;

public class BaseActivity extends Activity {

    private HttpUtils http = new HttpUtils();
    private HttpHandler handler;
    private final int Pregress_Dialog = 1;
    private NumberProgressBar bar;
    private TextView doneFlag;
    private View barView;
    private TextView totle;
    private long totleSize;
    private long currentSize;
    private PreferencesCookieStore cookieUtils;
    private boolean finishFlag;
    private NiftyDialogBuilder builder;
    public SharedPrefUtil sp;
    protected AlertDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        sp = new SharedPrefUtil(getApplicationContext(), Constants.SHARE_NAME);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    protected void showShortToast(int pResId) {
        showShortToast(getString(pResId));
    }

    protected void showLongToast(String pMsg) {
        Toast.makeText(this, pMsg, Toast.LENGTH_LONG).show();
    }

    protected void showShortToast(String pMsg) {
        Toast.makeText(this, pMsg, Toast.LENGTH_SHORT).show();
    }

    protected boolean hasExtra(String pExtraKey) {
        if (getIntent() != null) {
            return getIntent().hasExtra(pExtraKey);
        }
        return false;
    }

    protected void openActivity(Class<?> pClass) {
        openActivity(pClass, null);
    }

    protected void openActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(this, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivity(intent);
    }

    protected void openActivity(String pAction) {
        openActivity(pAction, null);
    }

    protected void openActivity(String pAction, Bundle pBundle) {
        Intent intent = new Intent(pAction);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivity(intent);
    }

    protected void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void finish() {
        super.finish();
        // overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    public void defaultFinish() {
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    public Dialog onCreateDialog(int id) {
        switch (id) {
            case Pregress_Dialog:
                LayoutInflater inflater = (LayoutInflater) BaseActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                barView = inflater.inflate(R.layout.download_dialog, null);
                bar = (NumberProgressBar) barView.findViewById(R.id.download_progressbar);
                totle = (TextView) barView.findViewById(R.id.totle);
                doneFlag = (TextView) barView.findViewById(R.id.done);
                doneFlag.setVisibility(View.GONE);
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) {
                    doneFlag.setTextColor(Color.WHITE);
                }
                bar.setVisibility(View.VISIBLE);
                builder = new NiftyDialogBuilder(BaseActivity.this, R.style.dialog_untran);
                Effectstype effect = Effectstype.Fall;
                builder.isCancelableOnTouchOutside(false);
                builder.setTypeface(HD_Application.TEXT_TYPE);
                builder.setCancelable(false);
                builder.setCustomView(barView, BaseActivity.this)
                        .withTitle(getString(R.string.download_dialog_title))
                        .withMessage("")
                        .withIcon(getResources().getDrawable(R.drawable.app_icon))
                        .withDuration(300)
                        .withEffect(effect)
                        .withButton1Text(getString(R.string.cancel)).setButton1Click(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        handler.cancel();
                        removeDialog(Pregress_Dialog);
                        if (finishFlag)
                            defaultFinish();
                    }
                });
                break;
        }
        return builder;
    }

    @Override
    public void onPrepareDialog(int id, Dialog dialog) {
        //super.onPrepareDialog(id, dialog);
        switch (id) {
            case Pregress_Dialog:
                double result = (double) (totleSize / 1024) / 1024;
                DecimalFormat df = new DecimalFormat("###0.00");
                totle.setText(df.format(result) + "M");
                bar.setMax(new Long(totleSize).intValue() / 100);
                bar.setProgress(new Long(currentSize).intValue() / 100);
                this.builder.setCustomView(barView, BaseActivity.this);
                break;
        }
    }

    public int getConnectedType(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }

    public void download(String net_addr, final String downloadDir, final String unZipDir, final Handler mHandler, boolean isfinish) {
        if (getConnectedType(BaseActivity.this) == -1) {
            showShortToast(R.string.network_error);
            mHandler.sendEmptyMessage(10);
            return;
        }
        finishFlag = isfinish;
        showDialog(Pregress_Dialog);
        handler = http.download(net_addr, downloadDir, false, false,
                new RequestCallBack<File>() {

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        totleSize = total;
                        currentSize = current;
                        showDialog(Pregress_Dialog);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        bar.setVisibility(View.GONE);
                        totle.setVisibility(View.GONE);
                        doneFlag.setVisibility(View.VISIBLE);
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                FileUtils.unZip(downloadDir, unZipDir);
                                mHandler.sendEmptyMessage(0);
                                removeDialog(Pregress_Dialog);
                                File delFile = new File(downloadDir);
                                if (delFile.exists()) {
                                    delFile.delete();
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        showShortToast(R.string.download_failed);
                        removeDialog(Pregress_Dialog);
                        mHandler.sendEmptyMessage(10);
                    }
                }

        );

    }

    protected ProgressDialog showProgressDialog(String pTitle, String pMessage, DialogInterface.OnCancelListener pCancelClickListener) {
        progressDialog = ProgressDialog.show(this, null, pMessage, true, false);
        progressDialog.setOnCancelListener(pCancelClickListener);
        return (ProgressDialog) progressDialog;
    }

    protected void dismissDialog() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}